package persistent.prestige.demo.netty.time;

import java.util.Date;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class TimeServer {
	
	public void bind(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
			         .channel(NioServerSocketChannel.class)
			         .option(ChannelOption.SO_BACKLOG, 1024)
			         .childHandler(new ChildChannelHandler());
			
			// 绑定短裤，同步等待成功
			System.out.println("服务器启动成功。。。。");
			ChannelFuture f = bootstrap.bind(port).sync();
			
			//等到服务端监听短裤关闭
			f.channel().closeFuture().sync();
			
		} finally {
			// 线程池资源释放
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	private static class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

		@Override
		protected void initChannel(SocketChannel sc) throws Exception {
			// TODO Auto-generated method stub
			sc.pipeline().addLast(new LineBasedFrameDecoder(1024));
			sc.pipeline().addLast(new StringDecoder());
			sc.pipeline().addLast(new TimeServerHandler());
		}
		
	}
	
	private static class TimeServerHandler extends ChannelHandlerAdapter {
		
		private int counter;

		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			// TODO Auto-generated method stub
			String body = (String)msg;
			System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter);
			
			String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? 
					new Date(System.currentTimeMillis()).toString() : "Bad Order";
					
			ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
			
			System.out.println("将响应发送给客户端....");
			ctx.writeAndFlush(resp);
					
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
			cause.printStackTrace();
			ctx.close();
		}
		
		
		
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int port = 8080;
		try {
			new TimeServer().bind(port);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
